package pCloud;

import java.util.HashMap;

/**
 * @author anhdinh
 * Handle access to the resource. It keeps a map of all the connections to the resources, for quick access.
 * 
 * The connections to resources are indexed by strings. 
 */
public class ResourceController {

	private HashMap<String,ResourceConnection> connections;
	public static final int SQL_DATATYPE = 1;
	public static final int NOSQL_DATATYPE = 2;
	
	private ResourceFactory sqlFactory, noSqlFactory; 
	
	public ResourceController(){
		connections = new HashMap<String,ResourceConnection>();
		sqlFactory = new SQLResourceFactory();
		noSqlFactory = new NoSQLResourceFactory();
	}
	
	private void addConnection(String id, ResourceConnection conn){
		connections.put(id,conn);
	}
	
	/**
	 * Return the connection to the resource specified in id. If the connection doesn't exist,
	 * create a new one and add to the list
	 * @param id
	 */
	public ResourceConnection createConnection(String driver, String id, String username, String password, int type) {
		if (connections.containsKey(id))
			return connections.get(id);
		else {
			ResourceConnection conn;

			if (type == SQL_DATATYPE) {
				conn = sqlFactory.createResourceConnection(driver, id, username, password);
			} else
				conn = noSqlFactory.createResourceConnection(driver, id, username, password);

			connections.put(id, conn);
			return conn;

		}
	}
}
